package com.baidu.foodrecipe.data.repository

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import com.baidu.foodrecipe.data.local.LocalDataSource
import com.baidu.foodrecipe.data.local.entity.RecipesEntity
import com.baidu.foodrecipe.data.local.RoomResult
import com.baidu.foodrecipe.data.local.entity.FavoriteEntity
import com.baidu.foodrecipe.data.model.FoodRecipe
import com.baidu.foodrecipe.data.model.Joke
import com.baidu.foodrecipe.data.remote.NetworkResult
import com.baidu.foodrecipe.data.remote.RemoteDataSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Response
import retrofit2.http.QueryMap

class Repository(val context: Context) {
    private val networkApi = RemoteDataSource.api
    private val roomDao = LocalDataSource.getDao(context)

    //------------------Retrofit2-----------------------
    /*
      会回调请求的状态
        正在发起请求
        请求成功
        请求失败
     */
    suspend fun getRecipes(@QueryMap params: Map<String, String>): Flow<NetworkResult> {
        //创建flow对象
        val mFlow = MutableStateFlow<NetworkResult>(NetworkResult.Loading)

        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            val recipeResponse = networkApi.getRecipes(params)
            if (recipeResponse.isSuccessful) {
                //告诉外部成功请求的数据
                mFlow.value = NetworkResult.Success(recipeResponse.body())
            } else {
                //告诉外部的原因
                mFlow.value = NetworkResult.Failure(recipeResponse.message())
            }
        }
        return mFlow
    }

    suspend fun getRecipes(
        @QueryMap params: Map<String, String>,
        callback: (result: NetworkResult) -> Unit = { }
    ) {
        //创建flow对象
        callback(NetworkResult.Loading)

        val recipeResponse = networkApi.getRecipes(params)
        if (recipeResponse.isSuccessful) {
            //告诉外部成功请求的数据
            callback(NetworkResult.Success(recipeResponse.body()))
        } else {
            //告诉外部的原因
            callback(NetworkResult.Failure(recipeResponse.message()))
        }
    }

    suspend fun getJokes(apiKey: String): Joke? {
        val response = networkApi.getJokes(apiKey)
        return if (response.isSuccessful) {
            response.body()
        } else {
            null
        }
    }

    //----------------------Room------------------------
    //从数据库中获取数据
    suspend fun getRecipes(): Flow<RoomResult> {
        val flow = MutableStateFlow<RoomResult>(RoomResult.Loading)
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            val data = roomDao.getRecipes()
            flow.value = RoomResult.Success(data)
        }
        return flow
    }

    suspend fun insertRecipe(entity: RecipesEntity) {
        roomDao.insertRecipe(entity)
    }


    //查询所有的收藏食谱数据
    fun getFavoriteRecipes(): Flow<List<FavoriteEntity>> {
        return roomDao.getFavoriteRecipes()
    }

    //收藏一个食谱
    suspend fun insertFavoriteRecipe(
        entity: FavoriteEntity,
        callback: (start: Boolean) -> Unit = {}
    ) {
        withContext(Dispatchers.Main) {
            callback(true)
        }

        roomDao.insertFavoriteRecipe(entity)

        withContext(Dispatchers.Main) {
            callback(false)
        }
    }

    suspend fun removeFavoriteRecipe(
        entity: FavoriteEntity,
        callback: (start: Boolean) -> Unit = {}
    ) {
        withContext(Dispatchers.Main) {
            callback(true)
        }
        roomDao.removeFavoriteRecipe(entity)

        withContext(Dispatchers.Main) {
            callback(false)
        }
    }

    suspend fun deleteAllFavoriteRecipes() {
        roomDao.deleteAllFavoriteRecipes()
    }

}